// 验证码
export const verificaCode = (dom, width, height) => {
  // 生成随机数-函数
  const random = (min, max) => parseInt(Math.random() * (max - min) + min)
  // 将0-9 A-Z a-z 存入数组
  let lagryAscll = 65
  let lowAscll = 97
  const codeArr = []
  for (let i = 0; i < 62; i++) {
    if (i < 10) {
      codeArr[i] = i
    } else if (lagryAscll <= 90) {
      codeArr[i] = String.fromCharCode(lagryAscll)
      lagryAscll++
    } else {
      codeArr[i] = String.fromCharCode(lowAscll)
      lowAscll++
    }
  }

  // 生成随机颜色-函数
  const randomColor = (min, max) => {
    const r = random(min, max)
    const g = random(min, max)
    const b = random(min, max)
    return `rgb(${r},${g},${b})`
  }

  // 获取 canvas dom元素
  const canvas = document.querySelector(dom)
  const context = canvas.getContext('2d')
  const w = width
  const h = height
  // 填充背景色
  context.fillStyle = '#F5F7FA'
  // context.fillStyle = 'transparent'
  context.fillRect(0, 0, w, h)

  // 要返回的 随机验证码 字符串
  let results = ''
  // 生成随机验证码
  for (let i = 0; i < 4; i++) {
    const code = codeArr[random(0, codeArr.length)]
    // 随机字体大小
    context.font = random(18, 40) + 'px 微软雅黑'
    // 文字的基线
    context.textBaseline = 'top'
    // 设置字体的填充颜色
    context.fillStyle = randomColor(80, 180)
    context.save()
    // 位移
    context.translate(i * (w / 4) + 10, 5)
    // 随机单个验证码的旋转角度
    const deg = random(-30, 30)
    // 旋转
    context.rotate((deg * Math.PI) / 180)
    // 绘制文本
    context.fillText(code, 2, 2)
    context.restore()
    results += code
  }
  // 生成随机干扰线
  for (let i = 0; i < 5; i++) {
    context.beginPath()
    context.moveTo(random(0, w), random(0, h))
    context.lineTo(random(0, w), random(0, h))
    context.strokeStyle = randomColor(150, 255)
    context.closePath()
    context.stroke()
  }
  // 生成随机小圆点
  for (let i = 0; i < 40; i++) {
    context.beginPath()
    context.arc(random(0, w), random(0, h), 2, 0, 2 * Math.PI)
    context.closePath()
    context.strokeStyle = randomColor(170, 220)
    context.stroke()
  }
  return results
}
